use axum::{
    Router,
    response::{Html, IntoResponse},
    routing::get,
};
use reqwest::header::SET_COOKIE;
use std::{net::SocketAddr, process, time::Duration};
use tokio::time::sleep;

#[tokio::main]
async fn main() {
    // 1. 请求百度并获取 cookie
    let client = reqwest::Client::new();
    let resp = client.get("https://www.baidu.com/").send().await.unwrap();
    let cookies = resp.headers().get_all(SET_COOKIE);
    let cookie_str = cookies
        .iter()
        .next()
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.split(';').next())
        .unwrap_or("")
        .to_string();
    println!("获取到的cookie: {}", cookie_str);

    let app = {
        Router::new().route(
            "/",
            get(move || async move {
                let html = format!(
                    r#"
                        <html>
                        <head>
                        <script>
                        document.cookie = "{cookie_str}";
                        console.log('cookie注入成功:', document.cookie);
                        setTimeout(() => {{
                            location.href = '/';
                        }}, 2000);
                        </script>
                        </head>
                        <body>
                        <h1>cookie注入成功</h1>
                        </body>
                        </html>
                        "#
                );
                Html(html).into_response()
            }),
        )
    };

    let addr = SocketAddr::from(([127, 0, 0, 1], 8080));
    println!("本地服务器启动: http://{}", addr);

    webbrowser::open("http://localhost:8080").ok();
    // 创建一个异步任务来处理定时关闭
    tokio::spawn(async {
        sleep(Duration::from_secs(1)).await;
        println!("1秒时间到，正在关闭服务器...");
        process::exit(0);
    });
    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
